define(["angularAMD", "moment"], function (angularAMD, moment) {
    angularAMD.service('F0101Service', ['$rootScope', '$filter', '$translate', 'config', 'MMWService', '$mdDialog', '$mddProvider',
        function ($rootScope, $filter, $translate, config, $MMWService, $mdDialog, $mddProvider) {
            /**
             * options : {
             *      parent: parent
             *      wo_no: 工單編號
             *      op_no: 作業站編號
             *      machine_no: 設備編號
             *      position_no: 工位編號
             *      callback : function
             * }
             **/
            this.init = function (options) {
                var lot_no = '';
                var wo_no = '';
                var op_no = '';
                var machine_no = 'N/A';
                var position_no = $filter('translate')('F0101.NA');
                var material_opt = '';
                var seq_select='';
                var dispatch = false; //20210507 modify by 德義_林佳諺 for #0086310 設備grid
                var updateMachineInfo = () => {};
                var check_dispatch_machine = 0; // 20231103 modify by Alan for#0149409 : 是否為派工設備

                if(options){
                    lot_no = options.lot_no || '';
                    wo_no =  options.wo_no || '';
                    op_no = options.op_no || '';
                    machine_no = options.machine_no || 'N/A';
                    position_no = options.position_no || $filter('translate')('F0101.NA');
                    // 20230309 modify by Alan for#128217 : 上下料後更新設備訊息
                    updateMachineInfo = (typeof options.callback) === 'function' ? options.callback : () => {};
                    check_dispatch_machine = options.check_dispatch_machine != undefined ? +options.check_dispatch_machine : 0;
                }
                if(op_no) {
                    checkPlugIn({op_no: op_no}, function(data){
                        if(data.qty != 0 && data.qty != '0'){
                            dispatch = true;
                        }
                    });
                }

                //工單開窗 machine_no === 'N/A' 
                function loadWoNoList(condition, callback) {
                    $MMWService.showQueryListPNIG({
                        page_mode: 1,
                        pageRecord: 50,
                        notQuery: false,
                        condition: [{
                            name: $filter('translate')('common.queryList.wo_c'),
                            column_name: 'MONo',
                            query_mode: '2',
                            value: '',
                            modeList: [
                                {name:$filter('translate')('common.report.condition.equal'), code:'0'},
                                {name:$filter('translate')('common.report.condition.nequal'), code:'1'},
                                {name:$filter('translate')('common.report.condition.contain'), code:'2'},
                                {name:$filter('translate')('common.report.condition.ncontain'), code:'3'}
                            ]
                        }],
                        header: [
                            {label: $filter('translate')('common.queryList.wo_c'), code: 'page_no'},
                            {label: $filter('translate')('common.queryList.item_c'), code: 'productno'},
                            {label: $filter('translate')('common.queryList.item_n'), code: 'productname'},
                            {label: $filter('translate')('common.queryList.item_spec'), code: 'productversion'}
                        ],
                        setCondition: function (conditions) {
                            // 20231020 modify by Alan for#144406 : 取消传入“MOSTATE”的query_condition_info
                            return conditions;
                        },
                        selectCode: condition.wo_no || '',
                        confirm: function (selectItem) {
                            if (callback)
                                callback(selectItem);
                        }
                    });
                } 

                // 20231103 modify by Alan for#0149409 : 設備編號不為N/A且為派工設備時，請求page_mode: '1-1'
                function loadWoNoWithMachineNOList(condition, callback) {
                    $MMWService.showQueryListPNIG({
                        page_mode: '1-1',
                        pageRecord: 50,
                        notQuery: false,
                        condition: [{
                            name: $filter('translate')('common.queryList.wo_c'),
                            column_name: 'MONo',
                            query_mode: '2',
                            value: '',
                            modeList: [
                                {name:$filter('translate')('common.report.condition.equal'), code:'0'},
                                {name:$filter('translate')('common.report.condition.nequal'), code:'1'},
                                {name:$filter('translate')('common.report.condition.contain'), code:'2'},
                                {name:$filter('translate')('common.report.condition.ncontain'), code:'3'}
                            ]
                        }],
                        header: [
                            {label: $filter('translate')('common.queryList.wo_c'), code: 'page_no'},
                            {label: $filter('translate')('common.queryList.item_c'), code: 'productno'},
                            {label: $filter('translate')('common.queryList.item_n'), code: 'productname'},
                            {label: $filter('translate')('common.queryList.item_spec'), code: 'productversion'}
                        ],
                        setCondition: function (conditions) {
                            conditions.push({ column_name: 'DSE.EQUIPMENTNO', query_mode: '0', value: machine_no, merge_condition_model: 'AND' });
                            return conditions;
                        },
                        selectCode: condition.wo_no || '',
                        confirm: function (selectItem) {
                            if (callback)
                                callback(selectItem);
                        }
                    });
                }

                //作業站開窗
                function loadOpNoList(condition, callback) {
                    $rootScope.showQueryList({
                        key: 'page_no',
                        header : [
                            {label: $filter('translate')('common.queryList.op_c'), code: 'page_no'},
                            {label: $filter('translate')('common.queryList.op_n'), code: 'page_name'},
                            {label: $filter('translate')('F0101.queryList.material_opt'), code: 'material_opt_label'}
                        ],
                        query: function(conditions, feedback){
                            var content = {
                                page_mode: '33',
                                query_condition_info: []
                            };
                            content.query_condition_info.push({column_name: 'b.MONo', query_mode: '0', value: condition.wo_no, merge_condition_model: 'AND'});
                            content.query_condition_info.push({column_name: 'c.MaterialOption', query_mode: '1', value: 0, merge_condition_model: 'AND'});

                            pageNumberInfoGet(content, function(data){
                                var op_list = data || [];
                                if(data && data.length > 0){
                                    data.forEach(function(item){
                                        item.material_opt_label = $filter('translate')('F0101.queryList.material_opt_' + item.material_opt);
                                    });
                                }
                                feedback(op_list);
                            });
                        },
                        selectCode: condition.op_no || '',
                        confirm: function(selectItem, dialog){
                            dialog.hide();
                            if (callback) {
                                callback(selectItem);
                            }
                        }
                    });
                }

                //取得工位資訊
                function pageNumberInfoGet_seq(content, callback, errorback){
                    $MMWService.pageNumberInfoGet(content, function(itemList){
                        seq_select = itemList;
                        if(callback)
                            callback(itemList);
                    }, errorback);
                }

                //工位開窗
                function loadPositionNoList(condition, callback,dialog){
                    // 20200720 modify by Oliver for M#75114
                    $rootScope.showQueryList({
                        key:'page_no',
                        header : [
                            {label: $filter('translate')('F0101.queryList.position_no'), code: 'page_no'}
                        ],
                        query: function(conditions,feedback){
                            let content = {
                                page_mode : '28',
                                query_condition_info: []
                            }
                            // 20210506 modify by kaiinagami for M#90239 - 增加參數傳送(op_no:作業站),(machine_no:設備/產線)
                            content.query_condition_info.push({column_name: 'b.OPNO', query_mode: '0', value: options.op_no, merge_condition_model: 'AND'});
                            content.query_condition_info.push({column_name: 'd.EquipmentNo', query_mode: '0', value: options.machine_no, merge_condition_model: 'AND'});
                           
                            pageNumberInfoGet_seq(content, function(data){
                                data.push({
                                    page_no: $filter('translate')('F0101.NA'),
                                    page_name: "",
                                    page_desc: ""
                                });
                                feedback(data);
                            });
                            
                        },
                        confirm: function(selectItem,dialog_seq){
                            if (callback) {
                                dialog_seq.hide();
                                if(callback){
                                   callback(selectItem); 
                                }
                            }
                        }
                    });
                }

                //下料前檢查
                function beforeCutting(dialog, callback){
                    var msg = '';
                    var selectedList = $filter('filter')(dialog.material_detail, {isSelect: true}, true);
                    if(selectedList.length == 0){
                        msg = $filter('translate')('F0101.msg.at_least_chooese_one'); //請至少選擇一筆物料
                    } else {
                        for(var i = 0; i < selectedList.length; i++){
                            var item = selectedList[i];
                            if((+item.qty) <= 0){
                                msg = $filter('translate')('F0101.msg.qty_not_enough_cutting', {material_no: item.material_no}); //物料編號：XXX 目前數量為0，不允許下料。
                                break;
                            }
                        }
                    }
                    //20210610 modify by 德義林佳諺 for M#0086310:邏輯新增
                    //若設備grid有資料, 下料時檢查是否有點選至少一個設備
                    // 20220330 modify by Alan for#109464 : 新增設備grid卡控，避免無設備grid時無法下料
                    if (dialog.dispatch) {
                        var selectedDispatch = $filter('filter')(dialog.dispatch_details, {isSelect: true}, true);
                        msg = selectedDispatch.length == 0 
                            ? $filter('translate')('F0101.msg.select_dispatch')
                            : '';
                    }
                    if(msg == ''){
                        if (callback)
                            callback(selectedList);
                    }else{
                        $rootScope.showAlert(msg);
                    }
                }

                //下料作業
                function cuttingProcess(content, dialog, callback){//20210507 modify by 德義_林佳諺 for #0086310 增加dialog參數
                    // $rootScope.showToast('下料成功');
                    // if (callback)
                    //     callback();
                    if (dispatch){//20210507 modify by 德義_林佳諺 for #0086310 若有設備grid則做此下料動作
                        var dispatch_details = $filter('filter')(dialog.dispatch_details, {isSelect: true}, true);
                        var material_details = $filter('filter')(dialog.material_detail, {isSelect: true}, true);
                        var dispatch_content = {
                            mo_no:dialog.condition.wo_no,//工單號
                            op_no:dialog.condition.op_no,//作業站
                            area_no:dialog.area_no,//區域
                            equipment_no:dialog.condition.machine_no,
                            material_details:material_details,
                            dispatch_details:dispatch_details,
                            user_id:config.cache.account
                        };
                        dispatch_content.material_details.forEach(function(item){
                            if (item.material_plot_no == null || item.material_plot_no == undefined)
                                item.material_plot_no = 'N/A';
                        });
                        dispatchCuttingProcess(dispatch_content, function(data){
                            if(callback)
                                callback(data)
                        });
                    }else{
                        $MMWService.sendToServer({
                            uri : 'ServicesSTD.Module_MAT.cutting_process',
                            content : content,
                            success : function(data, response) {
                                $rootScope.showToast(response.Message);
                                if (callback)
                                    callback(data);
                            }
                        });
                    }
                }

                //物料移轉前檢查
                function beforeTransfer(dialog, callback){
                    var selectedList = $filter('filter')(dialog.material_detail, {isSelect: true}, true);
                    if(selectedList.length == 0){
                        $rootScope.showAlert($filter('translate')('F0101.msg.at_least_chooese_one')); //請至少選擇一筆物料
                    }else if(selectedList.length > 1){
                        $rootScope.showAlert($filter('translate')('F0101.msg.transfer_gt_one')); //一次只能轉移一筆物料
                    }else{
                        var materialItem = selectedList[0];
                        if(materialItem.put_in_place_type != '5'){
                            if(dialog.position_no === $filter('translate')('F0101.NA')){
                                dialog.position_no = 'N/A'
                            }
                            //物料編號：XXX，作業站編號：XXX，為工單發料，工位編號：XXX，不允許移轉!!
                            $rootScope.showAlert($filter('translate')('F0101.msg.put_in_place_type_cant_transdfer', {
                                material_no: materialItem.material_no,
                                op_no: dialog.op_no,
                                position_no: dialog.position_no
                            }));
                        }else if(!materialItem.feeding_qty){
                            //沒有上料數量，不允許轉移
                            $rootScope.showAlert($filter('translate')('F0101.msg.feeding_qty_empty'));
                        }else{
                            if (callback)
                                callback(materialItem);
                        }
                    }
                }

                //叫料前檢查
                function beforeDemand(dialog, callback){
                    var msg = '';
                    var selectedList = $filter('filter')(dialog.material_detail, {isSelect: true}, true);

                    if(selectedList.length <= 0){
                        msg = $filter('translate')('F0101.msg.at_least_chooese_one'); //請至少選擇一筆物料
                    }else{
                        selectedList.forEach(function(materialItem){
                            if(materialItem.manual_qty == null || +materialItem.manual_qty == 0){
                                if(msg !== ''){
                                    msg += '<br>';
                                }
                                msg += $filter('translate')('F0101.msg.manual_qty_empty', {material_no: materialItem.substitute_material_no});
                            }
                        });
                    }

                    if(msg == ''){
                        checkRepeatDemandImp(dialog, selectedList, function(material_detail){
                            if(material_detail && material_detail.length > 0){
                                if (callback)
                                    callback(material_detail);
                            }
                        });
                    }else{
                        $rootScope.showAlert(msg);
                    }
                }

                function checkRepeatDemandImp(dialog, selectedList, callback){
                    var material_detail = angular.copy(selectedList);
                    checkRepeatDemand(dialog, material_detail, 0, function(){
                        if (callback)
                            callback(material_detail);
                    });
                }

                //重複叫料確認(並移除material_detail不要重複叫料的資料)
                function checkRepeatDemand(dialog, material_detail, index, callback){
                    if(material_detail && index < material_detail.length){
                        var materialItem = material_detail[index];
                        if(materialItem.demand_state === '0'){ // 已叫料，詢問是否要重複叫料
                            if(materialItem.position_no === $filter('translate')('F0101.NA')){
                                materialItem.position_no = 'N/A'
                            }
                            $rootScope.showConfirm($filter('translate')('F0101.msg.is_demand_again', {
                                material_no: materialItem.substitute_material_no,
                                wo_no: dialog.wo_no,
                                op_no: dialog.op_no,
                                machine_no: dialog.machine_no,
                                position_no: materialItem.position_no,
                                demand_mode: $filter('translate')('F0101.demand_mode_' + materialItem.is_auto_demand)
                            }), function(dialog){
                                dialog.hide();
                                checkRepeatDemand(dialog, material_detail, ++index, callback);
                            }, function(dialog){
                                dialog.hide();
                                material_detail.splice(index, 1);
                                checkRepeatDemand(dialog, material_detail, index, callback);
                            });
                        } else {
                            checkRepeatDemand(dialog, material_detail, ++index, callback);
                        }
                    } else {
                        if (callback)
                            callback();
                    }
                }

                //叫料作業
                function materialDemandProcess(content, callback){
                    // $rootScope.showToast('叫料成功');
                    // if (callback)
                    //     callback();
                    $MMWService.sendToServer({
                        uri : 'ServicesSTD.Module_MAT.material_demand_process',
                        content : content,
                        success : function(data, response) {
                            $rootScope.showToast(response.Message);
                            if (callback)
                                callback(data);
                        }
                    });
                }

                //取得用料選項
                function getMaterialOption(condition, callback){
                    var _material_opt = '';
                    var content = {
                        page_mode: '33',
                        query_condition_info: []
                    };
                    if(condition.op_no && condition.op_no != ''){
                        content.query_condition_info.push({column_name: 'a.OPNo', query_mode: '0', value: condition.op_no, merge_condition_model: 'AND'});
                        if(condition.wo_no && condition.wo_no != '')
                            content.query_condition_info.push({column_name: 'b.MONo', query_mode: '0', value: condition.wo_no, merge_condition_model: 'AND'});
                        pageNumberInfoGet(content, function(data){
                            if(data && data.length > 0){
                                _material_opt = data[0].material_opt;
                            }
                            if(callback)
                                callback(_material_opt);
                        });
                    }else{
                        if(callback)
                            callback(_material_opt);
                    }
                }

                //查詢物料資訊
                function MaterialInventoryInfoGet(content, callback) {
                    if(content.position_no === $filter('translate')('F0101.NA')){
                        content.position_no = 'N/A';
                    }
                    $MMWService.sendToServer({
                        uri : 'ServicesSTD.Module_MAT.material_inventory_info_get',
                        content : content,
                        success : function(data){
                            if(!data.material_detail || data.material_detail.length == 0){
                                $rootScope.showAlert($filter('translate')('common.msg.no_data'));
                            }
                            if (dispatch){// 如果設備grid有顯示
                                $MMWService.sendToServer({
                                    uri : 'ServicesSTD.Module_MAT.dispatch_info_get',
                                    content : {lot_no:lot_no, op_no:op_no},
                                    success : function(item){
                                        //20210610 modify by 德義林佳諺 for #0086310:預設選取設備第一項
                                        if(item.dispatch_info_get_details.length > 0){
                                            item.dispatch_info_get_details[0].isSelect = true;
                                            data.dispatch_info_get_details = item.dispatch_info_get_details;
                                        }  
                                        if(callback)
                                            callback(data);
                                    }
                                });
                            }else{
                                if(callback)
                                callback(data);
                            }
                        }
                    });
                }
                //20210507 modify by 德義_林佳諺 for #0086310控制是否顯示派工grid
                function checkPlugIn(content, callback){
                    $MMWService.sendToServer({
                        uri:"ServicesSTD.Module_MAT.check_plugIn",
                        content:content,
                        success:function(data){
                            if (callback)
                                callback(data);
                        }
                    });
                }
                //20210507 modify by 德義_林佳諺 for #0086310取得設備grid資料
                function dispatchInfoGet(content, callback){
                    $MMWService.sendToServer({
                        uri : 'ServicesSTD.Module_MAT.dispatch_info_get',
                        content : content,
                        success: function (data) {
                            if (data.dispatch_info_get_details.length > 0)
                                data.dispatch_info_get_details[0].isSelect = true;
                            if(callback)
                                callback(data);
                        }
                    });
                }
                //20210507 modify by 德義_林佳諺 for #0086310下料(plgIn == 5才執行)
                function dispatchCuttingProcess(content, callback){
                    $MMWService.sendToServer({
                        uri:'ServicesSTD.Module_MAT.dispatch_cutting_process',
                        content:content,
                        success:function(data, response){
                            $rootScope.showToast(response.Message);
                            if (callback)
                                callback(data);
                        }
                    });
                }
                function pageNumberInfoGet(content, callback){
                    $MMWService.sendToServer({
                        uri: 'ServicesSTD.Module_SYS.page_number_info_get',
                        content : content,
                        success : function(data){
                            if (callback)
                                callback(data.page_number_info_get);
                        }
                    });
                }

                function beforeOpenDialog(callback) {
                    var materialInfo = {};
                    if (wo_no && wo_no != '' && op_no && op_no != '') {
                        getMaterialOption({wo_no: wo_no, op_no: op_no}, function(_material_opt){
                            if(_material_opt !== '0'){ //非發料點
                                material_opt = _material_opt;
                                if(material_opt =='3' || material_opt =='4'){ //作業站上料、工位上料，設備編號要N/A
                                    machine_no = 'N/A';
                                }
                                if(position_no === $filter('translate')('F0101.NA')){
                                    position_no = 'N/A'
                                }
                                var content = {
                                    wo_no: wo_no,
                                    op_no: op_no,
                                    machine_no: machine_no,
                                    position_no: position_no,
                                    material_opt: material_opt
                                };
                                MaterialInventoryInfoGet(content, function (data) {
                                    if(data != null){
                                        materialInfo  = data;
                                    }
                                    if (callback)
                                        callback(materialInfo);
                                });
                            }else{
                                $rootScope.showAlert($filter('translate')('F0101.msg.material_opt_cant_be_zero', {op_no: op_no}));
                            }
                        });
                    } else {
                        if (callback)
                            callback(materialInfo);
                    }
                }

                function openDialog(data) {
                    $mddProvider.UseForm('F0101', () =>{
                        $mdDialog.dialog(
                            'module/moduleF/program/F0101/F0101.html',
                            function (dialog) {
                                let dialogScope = dialog.getDialogScope()
                                dialog.condition = {
                                    wo_no: wo_no,
                                    op_no: op_no,
                                    machine_no: machine_no,
                                    position_no: position_no,
                                    material_opt: material_opt
                                },
                                dialogScope.$watch('dialog.condition.wo_no', (newVal, oldVal) => {
                                    dialog.condition.wo_no_display = newVal
                                })
                                dialogScope.$watch('dialog.condition.op_no', (newVal, oldVal) => {
                                    dialog.condition.op_no_display = newVal
                                })
                                dialogScope.$watch('dialog.condition.position_no', (newVal, oldVal) => {
                                    dialog.condition.position_no_display = newVal
                                })
                                return {
                                    css_url: 'module/moduleF/program/F0101/F0101.css',
                                    parent: options.parent,
                                    condition: {
                                        wo_no: wo_no,
                                        op_no: op_no,
                                        machine_no: machine_no,
                                        position_no: position_no,
                                        material_opt: material_opt
                                    },
                                    wo_no: data.wo_no,
                                    op_no: data.op_no,
                                    machine_no: data.machine_no,
                                    position_no: data.position_no,
                                    area_no: data.area_no,
                                    material_detail: data.material_detail || [],
                                    material_opt: '',
                                    demand_board_permission: (!config.cache.permissions || config.cache.permissions.indexOf('F0201') != -1), // 叫料看板權限
                                    cutting_board_permission: (!config.cache.permissions || config.cache.permissions.indexOf('F0202') != -1), // 下料看板權限
                                    material_borrow_board_permission: (!config.cache.permissions || config.cache.permissions.indexOf('F0301') != -1), // 借料权限
                                    material_return_board_permission: (!config.cache.permissions || config.cache.permissions.indexOf('F0302') != -1), // 还料权限
                                    List_PageConfig: {
                                        page: 0,
                                        page_count: 8
                                    }, //分頁設定
                                    List_filterValue: {
                                        material_no: ''
                                    },
                                    lot_no:lot_no,
                                    dispatch:dispatch,//控制是否顯示dispatch grid
                                    dispatch_details:data.dispatch_info_get_details,
                                    _event:{
                                        'station_no':{
                                            click:()=>{
                                                dialog.loadPositionNoList()
                                            },
                                            isDisabled:(dialog.condition.material_opt!='4')? 'Y': 'N',
                                        },
                                        'wo_no':{
                                            click:()=>{
                                                dialog.loadWoNoList()
                                            },
                                            isDisabled:(dialog.dispatch)? 'Y': 'N'
                                        },
                                        'op_no':{
                                            click:()=>{
                                                dialog.loadOpNoList();
                                            },
                                            isDisabled:(dialog.dispatch)? 'Y': 'N'
                                        },
                                        'list':{
                                            isShown: (dialog.dispatch)? 'Y': 'N'
                                        }
                                    },
                                    _fn:{
                                        // 20230606 add by 文蔚 for 語系問題，在toolbar第一個按鈕的display一定叫"確定"，要用display改名稱，但吃不到語系
                                        'Execute':{
                                            isShown:  'N'
                                        },
                                        'btn_demand':{
                                            click:()=>{
                                                dialog.openF0201()
                                            },
                                            isShown: (dialog.demand_board_permission && dialog.area_no && dialog.area_no != '') ? 'N':'Y'
                                            
                                        },
                                        'btn_PortionCutting':{
                                            click:()=>{
                                                dialog.openF0202()
                                            },
                                            isShown: (dialog.cutting_board_permission && dialog.area_no && dialog.area_no != '') ? 'N':'Y'
                                            
                                        },
                                        'btn_matetial_transport':{
                                            click:()=>{
                                                dialog.materialReturn()
                                            },
                                            isShown: (dialog.material_return_board_permission) ? 'N':'Y'
                                            
                                        },
                                        'btn_cutting':{
                                            click:()=>{
                                                dialog.cutting();
                                                updateMachineInfo();
                                            }
                                        },
                                        'btn_material_replace':{
                                            click:()=>{
                                                dialog.transfer()
                                            }
                                        },
                                        'btn_material_req':{
                                            click:()=>{
                                                dialog.demand()
                                            }
                                        },
                                        'btn_search':{
                                            click:()=>{
                                                dialog.query()
                                            }
                                        },
                                    },
                                    init: function() {
                                        if(dialog.condition.position_no === "N/A"){
                                            dialog.condition.position_no = $filter('translate')('F0101.NA');
                                        }
                                        if(dialog.dispatch){//20210610 modify by 德義林佳諺 for #0086310:預設選取設備第一項
                                            if(dialog.dispatch_details.length > 0){
                                                dialog.dispatch_details[0].isSelect = true;
                                            }
                                        }
                                        
                                    },
                                    loadWoNoList: function () {
                                        const callback = (data) => {
                                            dialog.condition.wo_no = data.page_no;
                                            dialog.condition.item_no = data.productno;
                                            // 除了工位機，清空作業站 & 工位 & 設備
                                            if(dialog.parent != 'E01'){
                                                dialog.condition.op_no = '';
                                                dialog.condition.machine_no = options.machine_no || 'N/A';
                                                dialog.condition.position_no = $filter('translate')('F0101.NA');
                                                dialog.condition.material_opt = '';
                                                dialog.material_detail = [];
                                            }
                                        }

                                        // 20231103 modify by Alan for#0149409 : 修正判斷邏輯
                                        if (dialog.condition.machine_no != 'N/A' && check_dispatch_machine === 1) {
                                            loadWoNoWithMachineNOList(dialog.condition, callback)
                                        } else {
                                            loadWoNoList(dialog.condition, callback);
                                        }
                                    },
                                    loadOpNoList: function () {
                                        if (dialog.condition.wo_no === '') {
                                            $rootScope.showAlert($filter('translate')('F0101.msg.wo_no_empty'));
                                        } else {
                                            loadOpNoList(dialog.condition, function (data) {
                                                dialog.condition.op_no = data.page_no;
                                                dialog.condition.material_opt = data.material_opt;
                                                if(data.material_opt == '3' || data.material_opt == '4'){ // 3: 作業站上料, 4: 工位上料
                                                    dialog.condition.machine_no = 'N/A';
                                                } else if(data.material_opt == '1' || data.material_opt == '2'){ //1:設備上料, 2: 產線上料
                                                    dialog.condition.machine_no = options.machine_no || 'N/A';
                                                }

                                                // 除了工位機，清空工位
                                                if(dialog.parent != 'E01'){
                                                    dialog.condition.position_no = $filter('translate')('F0101.NA');
                                                    dialog.material_detail = [];
                                                }
                                            });
                                        }
                                    },
                                    loadPositionNoList: function () {
                                        if (dialog.condition.op_no === '') {
                                            $rootScope.showAlert($filter('translate')('F0101.msg.op_no_empty'));
                                        } else {
                                            loadPositionNoList(dialog.condition, function(data){
                                                dialog.condition.position_no = data.page_no;
                                                if(dialog.condition.position_no === "N/A"){
                                                    dialog.condition.position_no = $filter('translate')('F0101.NA');
                                                }
                                            });
                                        }
                                    },
                                    selectAll: function () {
                                        dialog.isSelectAll = !dialog.isSelectAll;
                                        dialog.material_detail.forEach(function (detail) {
                                            detail.isSelect = dialog.isSelectAll;
                                        });
                                        //20210507 modify by 德義_林佳諺 for #0086310 当上料勾选一条，则设备grid 默认全勾选
                                        if (dialog.isSelectAll && dialog.dispatch && dialog.dispatch_details){
                                            dialog.dispatch_details.forEach(function(detail){
                                                detail.isSelect = true;
                                            });
                                            dialog.dispatchIsSelectAll = true;
                                        }
                                    },//20210507 modify by 德義_林佳諺 for #0086310当上料grid数据未勾选，则设备grid只默认勾选当前设备
                                    dispatchSelectAll: function () {
                                        dialog.dispatchIsSelectAll = !dialog.dispatchIsSelectAll;
                                        dialog.dispatch_details.forEach(function (detail) {
                                            detail.isSelect = dialog.dispatchIsSelectAll;
                                        });
                                    },
                                    selectMaterial: function (item, event) {
                                        event.stopPropagation();
                                        item.isSelect = !item.isSelect;
                                        //20210507 modify by 德義_林佳諺 for #0086310 当上料勾选一条，则设备grid 默认全勾选
                                        if(item.isSelect && dialog.dispatch && dialog.dispatch_details){
                                            dialog.dispatchIsSelectAll = true;
                                            dialog.dispatch_details.forEach(function (detail) {
                                                detail.isSelect = true;
                                            });
                                        }
                                    },//20210507 modify by 德義_林佳諺 for #0086310当上料grid数据未勾选，则设备grid只默认勾选当前设备
                                    dispatchSelectMaterial: function (item, event) {
                                        event.stopPropagation();
                                        item.isSelect = !item.isSelect;
                                    },
                                    query: function () {
                                        if(dialog.condition.op_no && dialog.condition.op_no != ''){
                                            MaterialInventoryInfoGet(dialog.condition, function (data) {
                                                if(data.position_no === "N/A"){
                                                    data.position_no = $filter('translate')('F0101.NA');
                                                }
                                                dialog.wo_no = data.wo_no;
                                                dialog.op_no = data.op_no;
                                                dialog.machine_no = data.machine_no;
                                                dialog.position_no = dialog.condition.position_no = data.position_no;
                                                dialog.area_no = data.area_no,
                                                dialog.material_detail = data.material_detail || [];
                                            });
                                        }else{
                                            $rootScope.showAlert($filter('translate')('F0101.msg.op_no_empty'));
                                        }
                                        checkPlugIn({op_no:op_no || dialog.condition.op_no}, function(data){
                                            if(data.qty != 0 && data.qty != '0'){
                                                dialog.dispatch = dispatch = true;
                                            }
                                        });
                                        var dispatch_content = {
                                            lot_no:dialog.lot_no,
                                            op_no:dialog.op_no
                                        };
                                        if (dialog.dispatch){
                                            dispatchInfoGet(dispatch_content, function(data){
                                                dialog.dispatch_details = data.dispatch_info_get_details || [];
                                            });
                                        }else{
                                            dialog.dispatch_details = [];
                                        }
                                        if(dialog.dispatch){//20210610 modify by 德義林佳諺 for #0086310:預設選取設備第一項
                                            if(dialog.dispatch_details.length > 0){
                                                dialog.dispatch_details[0].isSelect = true;
                                            }
                                        }
                                    },
                                    getMaterialStyle: function (item) {
                                        return $filter('translate')('F0101.material_style_' + ((item.material_no == item.substitute_material_no) ? '1' : '0'));
                                    },
                                    getMaterialLight: function (item) {
                                        return (item.light === '0') ? 'green' : 'red';
                                    },
                                    feeding: function (item, event) {
                                        // 上料
                                        event.stopPropagation();
                                        //20210507 modify by 德義_林佳諺 for #0086310 修改為依據是否有設備grid做後續動作
                                        var feed_content = {
                                            lot_no:lot_no,
                                            equipment_no:dialog.condition.machine_no,
                                            material_no:item.material_no,
                                            mo_no:dialog.condition.wo_no,
                                            input_material_no:item.substitute_material_no,
                                            material_lot_no:item.material_plot_no || 'N/A',
                                            op_no:dialog.condition.op_no,
                                            position_no:'N/A',
                                            user_id:config.cache.account
                                        };
                                        var selectItemList = $filter('filter')(dialog.dispatch_details, {isSelect:true}, true);
                                        feed_content.dispatch_info_details = selectItemList;
                                        if (dialog.dispatch){
                                            if(selectItemList.length == 0){
                                                $rootScope.showAlert($filter('translate')('F0101.msg.select_dispatch'));
                                                feed_content = {};
                                            }else{
                                                $mdDialog.serviceDialog('F0102Service',{
                                                    feed_content:feed_content,
                                                    wo_no: dialog.wo_no,
                                                    op_no: dialog.op_no,
                                                    machine_no: dialog.machine_no,
                                                    materialItem: item,
                                                    callback: function (){
                                                        dialog.query();
                                                        updateMachineInfo();
                                                    }
                                                });
                                            }
                                        }else{
                                            feed_content = {};
                                            $mdDialog.serviceDialog('F0102Service',{
                                                wo_no: dialog.wo_no,
                                                op_no: dialog.op_no,
                                                machine_no: dialog.machine_no,
                                                materialItem: item,
                                                callback: function (){
                                                    dialog.query();
                                                    updateMachineInfo();
                                                }
                                            });
                                        }
                                    },
                                    cutting: function () {
                                        // 下料
                                        beforeCutting(dialog, function(material_detail){
                                            var content = {
                                                wo_no: dialog.wo_no,
                                                op_no: dialog.op_no,
                                                machine_no: dialog.machine_no,
                                                // position_no: dialog.position_no,
                                                material_detail: material_detail
                                            };//20210507 modify by 德義_林佳諺 for #0086310增加dialog參數的傳送
                                            cuttingProcess(content, dialog, function(){
                                                dialog.query();
                                            });
                                        });
                                    },
                                    //20210621 add by德義家興for#89697:增加部份下料欄位
                                    btnPortionCutting: function(item, event){
                                        if (item.qty == 0) { //目前數量為0不允許使用部份下料功能,提示訊息
                                            $rootScope.showAlert($filter('translate')('F0101.msg.qty_not_enough_cutting', {material_no: item.material_no}));
                                        }else{
                                            var content = {
                                                material_item: item,
                                                wo_no: dialog.wo_no, //工單編號3
                                                op_no: dialog.op_no, //作業站編號6
                                                callback: function (){
                                                    dialog.query();
                                                }
                                            }
                                            $mdDialog.serviceDialog('F0104Service',content);
                                        }
                                    },
                                    materialBorrow: function (item, event) {
                                        // 20201208 modify by 外包 for M#82349: 增加借料功能
                                        if (item.put_in_place_type != '3') {
                                            $rootScope.showAlert($filter('translate')('F0101.msg.wo_no_send_material'));
                                            return;
                                        }
                                        event.stopPropagation();
                                        $mdDialog.serviceDialog('F0301Service', {
                                            wo_no: dialog.wo_no,
                                            op_no: dialog.op_no,
                                            machine_no: dialog.machine_no,
                                            position_no: dialog.position_no,
                                            materialItem: item,
                                            callback: function () {
                                                dialog.query();
                                            }
                                        });
                                    },
                                    materialReturn: function () {
                                        // 20201208 modify by 外包 for M#82349: 增加还料功能
                                        let selected = dialog.material_detail.filter(m => m.isSelect);
                                        if (selected.length == 0) {
                                            $rootScope.showAlert($filter('translate')('common.msg.plz_select_one'));
                                            return;
                                        }
                                        if (selected.length != 1){
                                            $rootScope.showAlert($filter('translate')('F0101.msg.only_select_one'));
                                            return;
                                        }
                                        if (selected[0].put_in_place_type != '3') {
                                            $rootScope.showAlert($filter('translate')('F0101.msg.wo_no_send_material'));
                                            return;
                                        }
                                        $mdDialog.serviceDialog('F0302Service', {
                                            wo_no: dialog.wo_no,
                                            op_no: dialog.op_no,
                                            machine_no: dialog.machine_no,
                                            position_no: dialog.position_no,
                                            materialItem: selected[0],
                                            callback: function () {
                                                dialog.query();
                                            }
                                        });
                                    },
                                    transfer: function () {
                                        // 物料移轉
                                        beforeTransfer(dialog, function(materialItem){
                                            if(materialItem.position_no === $filter('translate')('F0101.NA')){
                                                materialItem.position_no = 'N/A'
                                            }
                                            $mdDialog.serviceDialog('F0103Service',{
                                                wo_no: dialog.wo_no,
                                                op_no: dialog.op_no,
                                                machine_no: dialog.machine_no,
                                                position_no: materialItem.position_no,
                                                material_no: materialItem.material_no,
                                                substitute_material_no: materialItem.substitute_material_no,
                                                material_plot_no: materialItem.material_plot_no,
                                                put_in_place_type: materialItem.put_in_place_type,
                                                callback: function(){
                                                    dialog.query();
                                                }
                                            });
                                        });
                                    },
                                    demand: function () {
                                        // 叫料
                                        beforeDemand(dialog, function(material_detail){
                                            var content = {
                                                wo_no: dialog.wo_no,
                                                op_no: dialog.op_no,
                                                machine_no: dialog.machine_no,
                                                // position_no: dialog.position_no,
                                                material_detail: material_detail
                                            };
                                            materialDemandProcess(content, function(){
                                                dialog.query();
                                            });
                                        });
                                    },
                                    back: function () {
                                        dialog.hide();
                                        if (options.callback)
                                            options.callback();
                                    },
                                    getPages: function (list, PageConfig, filterItem) {
                                        //分頁
                                        if (list) {
                                            var temp_list = list.filter(function (item, index, array) {
                                                var isOK = true,
                                                    keys = Object.keys(filterItem);
                                                for (var i = 0; i < keys.length; i++) {
                                                    var key = keys[i];
                                                    if (isOK && item[key] != null && filterItem[key] && filterItem[key] != '') {
                                                        if (item[key].indexOf(filterItem[key]) == -1) {
                                                            isOK = false;
                                                            break;
                                                        }
                                                    }
                                                }
                                                return isOK;
                                            });
                                            if (PageConfig) {
                                                if (temp_list.length != 0) {
                                                    PageConfig.total_page = Math.ceil(temp_list.length / PageConfig.page_count);

                                                    if (PageConfig.page >= PageConfig.total_page) {
                                                        PageConfig.page = 0;
                                                    }
                                                    var index = PageConfig.page * PageConfig.page_count;
                                                    return temp_list.slice(index, index + PageConfig.page_count);
                                                } else {
                                                    PageConfig.total_page = 1;
                                                    PageConfig.page = 0;
                                                }
                                            } else {
                                                return temp_list;
                                            }
                                        } else {
                                            return list;
                                        }
                                    },
                                    openF0201: function(){
                                        $rootScope.changeProgram('F0201', {data:{ area_no: dialog.area_no}});
                                        dialog.hide();
                                    },
                                    openF0202: function(){
                                        $rootScope.changeProgram('F0202', {data:{ area_no: dialog.area_no}});
                                        dialog.hide();
                                    }
                                };
                            }
                        );
                    })
                }

                beforeOpenDialog(function (data) {
                    openDialog(data);
                });
            };
        }
    ]);
});
